/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：ButtonControlledScreen.java <br>
 * 创建时间：2013-12-18 下午8:44:03 <br>
 * 所属项目：GmudEX <br>
 * @author 12548 <br>
 */
package lostland.gmud.exv2.ui.core;

import java.util.Arrays;

import lostland.gmud.exv2.Game;
import lostland.gmud.exv2.blgframework.impl.BLGGraphics;
import lostland.gmud.exv2.blgframework.impl.SingleTouchHandler;

/**
 * 类名：ButtonControlledScreen <br>
 * 说明：纯虚拟按键操作了喵！
 *
 * @author 12548
 */
public abstract class ButtonControlledScreen extends FullScreen {

	public static int otx;

	public static int oty;

	int dx, dy;

	public boolean isDown = false;

	protected GmudWindow dummyBorder;

	/**
	 * @param instance
	 */
	public ButtonControlledScreen() {
		super();
	}

	public static boolean inbound(int bx, int by, int tx, int ty) {
		final int R = NewButton.RADIUS;
		int x = bx + R;
		int y = by + R;

		return (tx - x) * (tx - x) + (ty - y) * (ty - y) < R * R;
	}

	public boolean isInbound(NewButton b) {
		return b.inBound(otx, oty);
	}

	protected abstract void onButtonDown(NewButton b);

	public abstract void onButtonClick(NewButton b);

	protected abstract void show();

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onTouchDown(int, int)
	 */
	@Override
	protected void onTouchDown(int tx, int ty) {

		otx = SingleTouchHandler.t2x;
		oty = SingleTouchHandler.t2y;

		dx = otx;
		dy = oty;
		isDown = true;

		NewButton b = NewButton.inbound(otx, oty);

		if (b != null) {
//			Arrays.fill(NewButton.pressed, false);
			NewButton.pressed[b.id()] = true;
			refreshButtons();
			onButtonDown(b);
		}

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onTouchMove(int, int)
	 */
	@Override
	protected void onTouchMove(int tx, int ty) {
//		GmudGame.logWarning("bts", "oTM");

		otx = SingleTouchHandler.t2x;
		oty = SingleTouchHandler.t2y;

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onTouchUp(int, int)
	 */
	@Override
	protected void onTouchUp(int tx, int ty) {
		isDown = false;
		Arrays.fill(NewButton.pressed, false);
		refreshButtons();
		NewButton b = NewButton.inbound(otx, oty);

		if (b == NewButton.inbound(dx, dy)) {
			onButtonClick(b);
		}

	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.ui.core.DialogScreen#onClick(int, int)
	 */
	@Override
	protected void onClick(int tx, int ty) {
		isDown = false;

		NewButton b = NewButton.inbound(otx, oty);

		Arrays.fill(NewButton.pressed, false);
		refreshButtons();
		if (b == NewButton.inbound(dx, dy)) {
			onButtonClick(b);
		}
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.CScreen#present(float)
	 */
	@Override
	public void present(float deltaTime) {
		show();
	}


	public static void refreshButtons() {
		BLGGraphics g = (BLGGraphics) Game.getInstance().getGraphics();
		Game.getInstance().SecondFB.eraseColor(0);
		for (NewButton i : NewButton.values()) {
			g.draw2ndPixmap(i.getPixmap(), i.x(), i.y());
		}
	}

}
